const app = getApp();
const cloud = require('../../../utils/api.js');
const towxImg = require('../../../utils/towxImg');
const { getCloudFunctionData, getCloudFunctionDataDetail } = require("../../../utils/cloudRequest.js");

Page({
  /**
   * 页面的初始数据
   */
  data: {
    type: "",
    gather: "",
    page: 1,
    pageSize: 20,
    total: 0,
    dataList: [],
    drawerActive: 1,
    drawerActiveId: '',
    scrollTop: 0,
    hide: app.globalData.hide,
    showDrawer: false,
    showAnswer: true,
    handleHidden: false,
    topicDetail: {}
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const { type, gather } = options;
    const { hide } = this.data;

    this.setData({
      type,
      gather
    });

    // if (hide) {
    //   wx.showModal({
    //     title: '提示',
    //     content: '该集合暂未收录题目',
    //     showCancel: false,
    //     complete: (res) => {
    //       if (res.confirm) {
    //         wx.navigateBack();
    //       }
    //     }
    //   })
    // } else {
    this.getStudyData(true);
    // }
  },

  // 共享数据
  async getStudyData(isLoad) {
    wx.showLoading({
      title: 'Loading...',
    })
    const that = this;
    let { drawerActive, drawerActiveId, dataList, type, gather, page, pageSize } = that.data;
    // drawerActive = wx.getStorageSync(type + "_index") || 1;
    // drawerActiveId = wx.getStorageSync(type + "_id") || '';
    wx.setNavigationBarTitle({
      title: type,
    });

    const res = await getCloudFunctionData({ gather, page, pageSize });
    let arr = res.data;
    if (arr.length == 0) {
      wx.hideLoading();
      wx.showToast({
        title: '没有更多了～',
        icon: 'none'
      })
      // wx.showModal({
      //   title: '提示',
      //   content: '没有更多了～',
      //   showCancel: false,
      //   complete: (res) => {
      //     if (res.confirm) {
      //       wx.navigateBack();
      //     }
      //   }
      // })
      return;
    }

    dataList = dataList.concat(arr);
    this.setData({
      total: res.total,
      dataList,
      // drawerActive,
      // drawerActiveId,
      page: page + 1
    })

    if (isLoad) {
      if (drawerActive && drawerActiveId) {
        this.getDeatil(gather, drawerActiveId, drawerActive);
      } else {
        this.getDeatil(gather, dataList[0]._id, drawerActive);
      }
    } else {
      wx.hideLoading();
    }
    // if (!isLoad) wx.hideLoading();
    // if (isLoad && drawerActive != 1) {
    //   wx.showToast({
    //     title: "已为你定位到上次位置",
    //     icon: "none",
    //   });
    // }
    return

    cloud.cloudGet(gather, {}, true).then(res => {
      let arr = res;
      arr.forEach((item, index) => {
        item.sort = index + 1
      })

      if (arr.length == 0) {
        wx.showModal({
          title: '提示',
          content: '该集合暂未收录题目',
          showCancel: false,
          complete: (res) => {
            if (res.confirm) {
              wx.navigateBack();
            }
          }
        })
        return;
      }
      arr.forEach(i => {
        i.catalogue = i.topic.replaceAll('#### ', '');
        i.topic = i.topic.replaceAll('\\n', '\n');
        i.answer = i.answer.replaceAll('\\n', '\n').replaceAll('\\=', '=').replaceAll('\\{', '{').replaceAll('\\}', '}').replaceAll('\\t', '\t');

        // i.topic = app.towxml(i.topic, "markdown", {
        //   base: '',
        //   theme: 'light'
        // });
        // i.answer = app.towxml(i.answer, "markdown", {
        //   base: '',
        //   theme: 'light'
        // });
        i.topic = towxImg.dealWithRichText(i.topic);
        i.answer = towxImg.dealWithRichText(i.answer);

      })
      that.setData({
        dataList: arr,
        drawerActive,
      });
      wx.hideLoading();
      if (drawerActive != 1) {
        wx.showToast({
          title: "已为你定位到上次位置",
          icon: "none",
        });
      }
    });
  },

  async getDeatil(gather, id, sort) {
    wx.showLoading({
      title: 'Loading...',
    })
    const { type } = this.data;
    let topicDetail = await getCloudFunctionDataDetail({ gather, id });
    // console.log(topicDetail);

    topicDetail.sort = sort;
    topicDetail.answer = towxImg.dealWithRichText(topicDetail.answer);

    this.setData({
      topicDetail,
      drawerActive: sort
    })
    // wx.setStorageSync(type + "_index", sort);
    // wx.setStorageSync(type + "_id", topicDetail._id);

    wx.hideLoading();
    this.goToTop();
  },

  clickTopicList(e) {
    const { id, index } = e.currentTarget.dataset;
    const { gather } = this.data;
    // console.log(gather, id, index);
    this.getDeatil(gather, id, index + 1)
    this.setData({
      showDrawer: false,
      drawerActive: index + 1
    })
  },

  next() {
    const { drawerActive, dataList, gather, total } = this.data;
    if (drawerActive >= total) {
      wx.showToast({
        title: "没有更多了...",
        icon: "none",
      });
      return;
    }
    const id = dataList[drawerActive]._id;
    const sort = drawerActive + 1;
    this.getDeatil(gather, id, sort);
  },

  prev() {
    const { drawerActive, dataList, gather } = this.data;
    if (drawerActive - 2 < 0) {
      wx.showToast({
        title: "已经到头了...",
        icon: "none",
      });
      return;
    }
    const id = dataList[drawerActive - 2]._id;
    const sort = drawerActive - 1;
    this.getDeatil(gather, id, sort);
  },

  bindscrolltolower() {
    this.getStudyData(false);
  },

  goToTop() {
    this.setData({
      scrollTop: 0,
    });
  },

  checkCatalogue() {
    this.setData({
      showDrawer: !this.data.showDrawer,
      handleHidden: true,
    });
  },

  recite() {
    const that = this;
    const { showAnswer, handleHidden } = that.data;
    if (handleHidden) {
      that.setData({
        handleHidden: false,
      });
      return;
    }
    that.setData({
      showAnswer: !showAnswer,
    });
  },

  touch() {
    this.setData({
      handleHidden: true,
    });
  },

  // onPageScroll(e) {
  //   this.setData({
  //     scrollTop: e.scrollTop,
  //   });
  // },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() { },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() { },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() { },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() { },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() { },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() { },
});
